﻿using System.Threading.Tasks;

namespace Sidvall.AuthorizationManager.UI
{
	public static class ViewModelManager
	{
		#region ExportSettingsAsync

		public static async Task ExportSettingsAsync(string fileName, object value)
		{
			Task task = null;
			try
			{
				var dialogContext = new Sidvall.UI.Dialogs.SaveFileDialogContext()
				{
					DefaultExtension = ".txt",
					FileName = fileName,
					Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*",
					InitialFolder = Sidvall.IO.FolderType.MyDocuments,
				};
				fileName = await Sidvall.UI.SystemContext.Current.DialogManager.SaveFileAsync(dialogContext);
				if (string.IsNullOrWhiteSpace(fileName))
					return;
				var content = Sidvall.Serialization.SerializerManager.Current.SerializeObject(value, Serialization.Formatting.Indented);
				await Sidvall.SystemContext.Current.SystemStorageManager.WriteAllTextAsync(fileName, content);
			}
			catch (System.Exception ex)
			{
				task = Sidvall.UI.SystemContext.Current.DialogManager.ShowErrorMessageAsync("Error", ex);
			}
			if (task != null)
				await task;
		}

		#endregion
		#region ImportSettingsAsync

		public static async Task<string> ImportSettingsAsync()
		{
			var dialogContext = new Sidvall.UI.Dialogs.OpenFileDialogContext()
			{
				DefaultExtension = ".txt",
				Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*",
				InitialFolder = Sidvall.IO.FolderType.MyDocuments,
			};
			var fileName = await Sidvall.UI.SystemContext.Current.DialogManager.OpenFileAsync(dialogContext);
			if (string.IsNullOrWhiteSpace(fileName))
				return null;
			return await Sidvall.SystemContext.Current.SystemStorageManager.ReadAllTextAsync(fileName);
		}

		#endregion
	}
}
